#---coding:utf-8---
# python 3.7.8
# 大量使用哔哩哔哩：偶尔有点小迷糊的创意和源码，感谢！
from tkinter import *
import os
from PIL import Image
import math
import tkinter.messagebox
from MyQR.myqr import run
from os import getcwd

# 边框大小
geo_num = "250x220"

def copy_girl():
    open('请复制.txt', 'w',encoding='utf-8')
    # 实现功能
    def writes(write_num,write_things):
        try:
            book = open('请复制.txt', 'r+',encoding='utf-8')
            for i in range(write_num):
                book.write(write_things)
            book.close()
        except:
            tkinter.messagebox.showerror("错误","这绝对不是复制姬的问题！")
        else:
            print("成功")


    #操作界面
    def function():
        global thing
        global num_in
        w = Tk()
        w.geometry("400x160")
        w.title("复制姬 v1.0 dev")  
        label1 = Label(w, text='请输入内容：', font=('Arial', 14)).place(x=10, y=10)
        label2 = Label(w, text='请输入遍数：', font=('Arial', 14)).place(x=10, y=50)
        thing = Entry(w,font=('Arial', 14))
        thing.place(x=120,y=15)
        num_in = Entry(w,font=('Arial', 14))
        num_in.place(x=120,y=55)

        def gets():
            global thing
            global num_in
            things = thing.get()
            try:
                num = int(num_in.get())
            except:
                tkinter.messagebox.showerror("错误","hentai！无路赛！你在下面塞别的东西干嘛？")
            else:
                writes(num,things)

        Button(w,text="复制！",font=('Arial', 14),command=gets).place(x=160,y=90)
        Label(w,text="copyright bilibili-whtry陈",font=("微软雅黑",10)).place(x=240,y = 135)

    function()

    mainloop()

def ITT():
    global num
    global num2
    global num3
    num = 10000
    num2 = 20000
    num3 = 30000
    # 完成提示
    def yes(re):
        tkinter.messagebox.showinfo("结果","转换成功,文件名为："+re)
    def no():
        tkinter.messagebox.showerror("结果","转换失败")
    # 转图片

    def ip():
        global num
        global numl
        nm = en1.get()
        numl = str(num)+".bmp"
        try:
            def encode(text):
                str_len = len(text)
                width=math.ceil(str_len**0.5)
                im=Image. new("RGB",(width, width), 0x0)
            
                x,y=0,0
                for i in text:
                    index= ord(i)
                    rgb=(0, (index & 0xFF00)>> 8, index & 0xFF)
                    im.putpixel((x, y),rgb)
                    if x== width - 1:
                        x=0
                        y +=1
                    else:
                        x+=1
                return im

            if __name__=='__main__':
                im= encode (nm)
                im.save(numl)
                num += 1
        except:
            no()
        else:
            yes(numl)
    # 转文字
    def out():
        global num2
        global numl2
        numl2 = str(num2)+".txt"
        image = en2.get()
        try:
            def decode(im):
                width,height = im.size
                lst = []
                for y in range(height):
                    for x in range(width):
                        red,green,blue = im.getpixel((x,y))
                        if(blue | green | red) == 0:
                            break
                        index = (green<<8) + blue
                        lst.append(chr(index))
                return ''.join(lst)

            if __name__=='__main__':

                all_text = decode(Image.open(image,"r"))
                with open (numl2,"w",encoding = "utf-8") as f:
                    f.write(all_text)
        except:
            no()
        else:
            yes(numl2)
            num2 +=1

    def ip2():
        global num3
        global numl3
        nm = en3.get()+".txt"
        numl3 = str(num3)+".bmp"
        try:
            def encode(text):
                str_len= len(text)
                width=math.ceil(str_len**0.5)
                im=Image. new("RGB",(width, width), 0x0)
            
                x,y=0,0
                for i in text:
                    index= ord(i)
                    rgb=(0, (index & 0xFF00)>> 8, index & 0xFF)
                    im.putpixel((x, y),rgb)
                    if x== width - 1:
                        x=0
                        y +=1
                    else:
                        x+=1
                return im

            if __name__=='__main__':
                with open(nm,encoding="utf-8")as f:
                    all_text=f.read()
                    
                    im= encode (all_text)
                    im.save(numl3)
        except:
            no()
        else:
            yes(numl3)
            num3 +=1
            
    w = Tk()
    w.geometry("780x505")
    w.title("转换器 v1.0")
    lb1 = Label(w,text="需要转换的文本和图片请和程序放在同一文件夹下",font=("微软雅黑",25))
    lb1.pack()
    lb2 = Label(w,text="请输入需要转换的内容",font=("微软雅黑",20))
    lb2.pack()
    en1 = Entry(w)
    en1.pack(pady=10)
    bt1 = Button(w,text = "转图片",font=("微软雅黑",20),padx=50,command=ip)
    bt1.pack()
    lb3 = Label(w,text="请输入需要转换的图片（记得加后缀名）",font=("微软雅黑",20))
    lb3.pack()
    en2 = Entry(w)
    en2.pack(pady=10)
    bt2 = Button(w,text = "转文字",font=("微软雅黑",20),padx=50,command=out)
    bt2.pack()
    lb4 = Label(w,text="请输入文件名(txt属性！)",font=("微软雅黑",20))
    lb4.pack()
    en3 = Entry(w)
    en3.pack(pady=10)
    bt3 = Button(w,text = "转图片",font=("微软雅黑",20),padx=50,command=ip2)
    bt3.pack()
    Label(w,text="copyright bilibili-whtry陈",font=("微软雅黑",10)).pack()
    w.mainloop()

def qr():
    def main(
        words: str,
        level = 'H',
        version = 20,
        save_dir = getcwd(),
        save_name = None,
        picture = None,
        colorized = True
    ):
        '''
        # 必选参数
        + words: 要表示的文字,不支持中文
        # 可选参数
        + picture: 背景图片路径,可选,默认为空,即生成普通二维码
        + save_dir: 生成的二维码存储位置, 默认为当前工作目录
        + save_name: 控制文件名, 格式可以是[jpg, png, bmp, gif].
        > 使用背景图片默认
        >> 背景图片文件名 + '_qrcode.png'
        > 不使用背景图片默认
        >> qrcode.png
        > 自定义
        + level: 纠错等级, 范围是L、M、Q、H，从左到右依次升高, 默认为"H": 超强纠错
        + colorized: 是否使用彩色, 默认使用
        + version: 二维码边长, 默认为20
        '''
        run(
            words=words,
            version=version,
            level=level,
            picture=picture,
            colorized=colorized,
            save_name=save_name,
            save_dir=save_dir
        )

    qr_win = Tk()
    qr_win.geometry("640x250")
    qr_win.title("二维码转换 v1.0")
    Label(qr_win,text="请输入需要转换的文字（不支持中文）",font=("微软雅黑",17)).pack()
    qr_words = Entry(qr_win,width=70)
    qr_words.pack()

    Label(qr_win,text="请输入纠错级别（L,M,Q,H，默认为最高'H，大写)'",font=("微软雅黑",17)).pack()
    qr_level = Entry(qr_win,width=70)
    qr_level.pack()

    Label(qr_win,text="请输入需要的背景（默认为无背景,请加后缀）",font=("微软雅黑",17)).pack()
    qr_pic = Entry(qr_win,width=70)
    qr_pic.pack()

    def use():
        # 防止无输入
        if qr_words.get() == "":
            tkinter.messagebox.showerror("错误","请输入内容")
        else:
            qr_in_words = qr_words.get()

        # 判断背景
        try:
            if qr_pic.get() == "":
                qr_in_pic = None
            else:
                qr_in_pic = qr_pic.get()
        except:
            tkinter.messagebox.showerror("错误","背景错误\n错误代码：qr100")

        # 判断后缀
        try:
            qr_in_pic_last_list = qr_in_pic.split(".")
            qr_in_pic_last_re = qr_in_pic_last_list[len(qr_in_pic)-1]
        except:
            qr_in_pic_last = None
        else:
            qr_in_pic_last = qr_in_pic_last_re
        
        # 判断纠错级别
        try:
            if qr_level.get() == "":
                qr_in_level = "H"
            else:
                qr_in_level = qr_level.get()
        except:
            tkinter.messagebox.showerror("错误","判断纠错级别错误\n错误代码：qr101")

        # 执行
        try:
            main(
                qr_in_words,
                level = qr_in_level,
                save_name = qr_in_pic_last,
                picture = qr_in_pic
            )
        except:
            tkinter.messagebox.showerror("错误","执行错误\n错误代码：qr102")

    Button(qr_win,text="制作！",font=("微软雅黑",14),width=10,command=use).pack()
    Label(qr_win,text="copyright bilibili-whtry陈",font=("微软雅黑",10)).pack()

    qr_win.mainloop()

def use():
    win = Tk()
    win.geometry(geo_num)
    win.title("工具姬 v1.1")
    Button(win,text="复制姬",font=("微软雅黑",20),width=10,command = copy_girl).pack()
    Button(win,text="图文互转",font=("微软雅黑",20),width=10,command = ITT).pack()
    Button(win,text="二维码生成器",font=("微软雅黑",20),width=10,command = qr).pack()
    Label(win,text="copyright bilibili-whtry陈",font=("微软雅黑",10)).pack()

def tips():
    tips = Tk()
    tips.geometry("600x145")
    tips.title("工具姬的小提示！")
    Label(tips,text="ITT工具可以将你想要转换的文字转换成蓝色的图片\n复制姬则可以批量复制你想复制的东西\n(复制出的东西在本软件目录)",font=("微软雅黑",15)).pack()
    def tips_off():
        tips.destroy()
        use()
    Button(tips,text="继续",font=("微软雅黑",10),width=10,command = tips_off).pack()
    Label(tips,text="copyright bilibili-whtry陈",font=("微软雅黑",5)).pack()
    
open_num = 0
try:
    tip = open("ci_shu.txt","r")
except:
    tip = open("ci_shu.txt","w")
else:
    open_num += 1
if open_num == 1:
    use()
elif open_num == 0:
    tips()

mainloop()